package com.atguigu.flink.watermark;

import com.atguigu.flink.function.MyUtil;
import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.TimerService;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

/**
 * Created by Smexy on 2023/2/28
 */
public class Demo6_Idleness
{
    public static void main(String[] args) {


        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 3333);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

        env.disableOperatorChaining();
        env.getConfig().setAutoWatermarkInterval(2000);

        env.setParallelism(6);

        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy
            .<WaterSensor>forMonotonousTimestamps()
            .withTimestampAssigner( (e, ts) -> e.getTs())
            // 如果当前并行度，10s内没有收到数据，就推出水印的发送，退休赋闲。一旦有数据产生了，就会重新参与水印的发送。
            .withIdleness(Duration.ofSeconds(10))
            ;

                env
                   .socketTextStream("hadoop103", 8888)
                   //只发给1号
                   .global()
                   .map(new WaterSensorMapFunction())
                   .assignTimestampsAndWatermarks(watermarkStrategy).name("wm")
                   .keyBy(WaterSensor::getId)
                   .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                   .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>()
                   {
                       @Override
                       public void process(String key, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                           List<WaterSensor> waterSensors = MyUtil.parseToList(elements);
                           out.collect(key + ":" + context.window() + " :" + waterSensors);
                       }
                   })
                   .print();


                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

    }
}
